package com.whut.work.user.controller;

import com.whut.work.base.model.Page;
import com.whut.work.user.model.User;
import com.whut.work.user.service.IUserService;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by zouy on 17-3-15.
 */
@Controller
@RequestMapping("/user")
public class UserCtrl {

    @Autowired
    private IUserService userService;

    @RequestMapping(value="/getUserPageList",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getUserPageList(HttpServletRequest request, int currentPage, int pageSize, String blurName){
        Map<String,Object> returnMap = new HashMap<String,Object>();

        try {
            Page<User> userPage = userService.getUserPageList(currentPage,pageSize,blurName);

            returnMap.put("page", userPage);
            returnMap.put("success", true);
        } catch (Exception e) {
            returnMap.put("message", "异常：获取失败!");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    @RequestMapping(value="/getCoursePageListByUserId",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getCoursePageListByUserId(HttpServletRequest request, int currentPage, int pageSize, Integer userId){
        Map<String,Object> returnMap = new HashMap<String,Object>();

        try {
            Map<String,Object> result = userService.getCoursePageListByUserId(currentPage,pageSize,userId);

            returnMap.put("value", result.get("value"));
            returnMap.put("message", result.get("message"));
            returnMap.put("success", true);
        } catch (Exception e) {
            returnMap.put("message", "异常：获取失败!");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    @RequestMapping(value="/addUserAvatar",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addOneGoods_pic(HttpServletRequest request, @RequestParam("file") MultipartFile file, ModelMap model){
        Map<String,Object> returnMap = new HashMap<String,Object>();
        System.out.println(file.getName());
        /*System.out.println("start-------------");
        String savePath = request.getSession().getServletContext().getRealPath("/WEB-INF/goods-imgs/");//存储路径
        System.out.println(ServletFileUpload.isMultipartContent(request));
        System.out.println(savePath);
        System.out.println(request);
        try {
            if (ServletFileUpload.isMultipartContent(request)) {
                List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
                System.out.println(items);
                for (FileItem item : items) {
                        System.out.println("helloosjfos");
                        String fileType = item.getName().substring(item.getName().lastIndexOf(".") + 1).toLowerCase();//文件类型
                        String fileName = new Date().getTime() + "." + fileType; //保存的文件名
                        String filePath = savePath + "\\" + fileName; //保存的文件路径
                        System.out.println(fileType+fileName+filePath+"---------");
                        System.out.println(savePath);

                        BufferedInputStream in = new BufferedInputStream(item.getInputStream());// 获得文件输入流
                        BufferedOutputStream out = new BufferedOutputStream(
                                new FileOutputStream(new File(filePath)));// 获得文件输出流
                        Streams.copy(in, out, true);// 开始把文件写到指定的上传文件夹
                        in.close();
                        out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }*/


        /****************************************************************/
        try {

            System.out.println("开始");


            String savePath = request.getSession().getServletContext().getRealPath("/avatar-img/");//存储路径
            File myPath = new File(savePath);
            if ( !myPath.exists()){//若此目录不存在，则创建之// 这个东西只能一级建立文件夹，两级是无法建立的。。。。。
                myPath.mkdir();}
            System.out.println(ServletFileUpload.isMultipartContent(request));
            System.out.println(savePath);

            String fileName = file.getOriginalFilename();

            System.out.println(fileName);

            BufferedInputStream bufrs = new BufferedInputStream(file.getInputStream());
            BufferedOutputStream out = new BufferedOutputStream(
                    new FileOutputStream(new File(savePath,fileName)));// 获得文件输出流
            byte[] by = new byte[1024];
            int ch = 0;
            while ((ch = bufrs.read(by)) != -1) {
                out.write(by);
            }
            out.flush();
            out.close();
            bufrs.close();

            returnMap.put("success", "头像上传成功");
        }catch (Exception e){
            e.printStackTrace();
        }
        return returnMap;
    }

    @RequestMapping(value="/addOneUser",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> addOneUser(HttpServletRequest request,String password, String type, String username, String sex,
                                         String origin, String graduate, String major, String tel, String picture,
                                         String number){
        Map<String,Object> returnMap = new HashMap<String,Object>();

        try {
            Map<String,Object> result = userService.addOneUser(password,type,username,sex,origin,graduate,major,tel,
                    picture,number);

            returnMap.put("value", result.get("value"));
            returnMap.put("message", result.get("message"));
            returnMap.put("success", true);
        } catch (Exception e) {
            returnMap.put("message", "异常：获取失败!");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    @RequestMapping(value="/getOneUser",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> getOneUser(HttpServletRequest request,String account, String password){
        Map<String,Object> returnMap = new HashMap<String,Object>();

        try {
            Map<String,Object> result = userService.getOneUser(account,password);

            returnMap.put("value", result.get("value"));
            returnMap.put("message", result.get("message"));
            returnMap.put("success", true);
        } catch (Exception e) {
            returnMap.put("message", "异常：获取失败!");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

    @RequestMapping(value="/updateOneUser",method= RequestMethod.POST)
    @ResponseBody
    public Map<String,Object> updateOneUser(HttpServletRequest request,String account, String password, String type, String username, String sex, String origin,
                                            String graduate, String major, String tel, String picture){
        Map<String,Object> returnMap = new HashMap<String,Object>();

        try {
            Map<String,Object> result = userService.updateOneUser(account,password,type,username,sex,origin,graduate,major,tel,
                    picture);

            returnMap.put("message", result.get("message"));
            returnMap.put("success", true);
        } catch (Exception e) {
            returnMap.put("message", "异常：失败!");
            returnMap.put("success", false);
            e.printStackTrace();
        }
        return returnMap;
    }

}
